package tas.co.in.controller.login;

import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import tas.co.in.dao.login.LoginConnect;
import tas.co.in.domain.logindomain.LoginInfoBean;

public class LoginController extends MultiActionController {

	private LoginConnect loginConnect;

	public void setLoginConnect(LoginConnect loginConnect) {
		this.loginConnect = loginConnect;
	}

	public ModelAndView validateUser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		LoginInfoBean infoBean = new LoginInfoBean();

		HttpSession session = request.getSession(true);

		infoBean.setUsername(request.getParameter("username"));
		infoBean.setPassword(request.getParameter("password"));

		LoginInfoBean resultList = loginConnect.validateLoginDetails(infoBean);

		if (resultList.getResult().equalsIgnoreCase("1")) {

			LoginInfoBean resultObject = loginConnect.getLoginUser(infoBean);

			session.setAttribute("userId", resultObject.getUserId());
			session.setAttribute("roleId", resultObject.getRoleId());
			session.setAttribute("userName", infoBean.getUsername());

		}

		return new ModelAndView("sharedJSP/BooleanResults", "resultObject",
				resultList.getResult());

	}
	
	/**
	 * this method will create the menu
	 * 
	 * @param request
	 * @param response
	 */
	public ModelAndView generateMenu(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession(true);
		
		LoginInfoBean login = new LoginInfoBean();
		
		login.setUsername(session.getAttribute("userName").toString());
		login.setUserId(session.getAttribute("userId").toString());
		login.setRoleId(session.getAttribute("roleId").toString());

		
		StringWriter menu = loginConnect.getMenu(login);
		
		if (menu.toString().contains("errorMenu:")) {
			return new ModelAndView("sharedJSP/MenuStructure", "menu", menu);
		}

		return new ModelAndView("sharedJSP/MenuStructure", "menu", menu);
	}
	
	public ModelAndView updateLogDetails(HttpServletRequest request,
						HttpServletResponse response){
		
		LoginInfoBean infoBean = new LoginInfoBean();

		HttpSession session = request.getSession(true);
		
		infoBean.setUsername(session.getAttribute("userName").toString());
		
		boolean resultList = loginConnect.updateLogDetails(infoBean);					
		
		return new ModelAndView("sharedJSP/BooleanResults", "resultObject",
				resultList);
	}

}
